package com.fingard.dsp.bank.directbank.weixin01;

import java.util.Random;

import com.fingard.crypto.DigestHelper;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IQRPay;
import com.fingard.dsp.bank.reqrespobj.qrpay.ReqGenQRInfo;
import com.fingard.dsp.bank.reqrespobj.qrpay.RetAtsGenQRInfo;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqUnifiedOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsUnifiedOrder;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;

public class WEIXIN01QRPay extends WxUnifiedOrder implements IQRPay {
	public RetAtsGenQRInfo genQRInfo(ReqGenQRInfo p_req) {
		RetAtsGenQRInfo retAts = new RetAtsGenQRInfo();
		retAts.rdSeq = p_req.rdSeq;
		
		try{
			ActSetItem actItem = this.getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId, p_req.appId, "unifiedorder");
			if(actItem != null){
				String appid = p_req.appId;
				if(StringHelper.isNullOrEmpty(appid)){
					appid = actItem.appId;
				}
				
				String mch_id = p_req.merchantId;
				if(StringHelper.isNullOrEmpty(mch_id)){
					mch_id = actItem.merchantId;
				}
				
				/*二维码中的内容为链接，形式为：weixin://wxpay/bizpayurl?sign=XXXXX&appid=XXXXX&mch_id=XXXXX&product_id=XXXXXX&time_stamp=XXXXXX&nonce_str=XXXXX*/
				//自1970年1月1日 0点0分0秒以来的秒数，10位数字
				String time_stamp = DateHelper.getSecsFrom1970();
				
				//随机字符串 String(32)
				Random random=new Random();
				long randLong = random.nextLong();
				randLong = random.nextLong();
				String nonce_str = time_stamp+String.format("%20d", randLong);
				nonce_str = DigestHelper.cryptoMD5RetHexStr(nonce_str.getBytes());
				
				String[] signParams = new String[5];
				
				signParams[0]="appid="+appid;
				signParams[1]="mch_id="+mch_id;
				signParams[2]="product_id="+p_req.rdSeq;
				signParams[3]="time_stamp="+time_stamp;
				signParams[4]="nonce_str="+nonce_str;
				
				String sign = signMessage(signParams, actItem.saltKey);
				
				retAts.respCode = "0";
				retAts.respInfo = "成功";
				retAts.qrInfo = "weixin://wxpay/bizpayurl?sign="+sign+"&appid="+appid+"&mch_id="+mch_id+"&product_id="+p_req.rdSeq+"&time_stamp="+time_stamp+"&nonce_str="+nonce_str;
			} else {
				retAts.respCode = "0";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "商户配置信息";
				retAts.qrInfo = "";
			}
		} catch(Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}
		
		return retAts;
	}
	
	public RetAtsUnifiedOrder submitQROrder(ReqUnifiedOrder p_req){
		return submitUnifiedOrder(p_req);
	}

	public RetAtsQueryOrder queryQRPay(ReqQueryOrder p_req){
		return queryUnifiedOrder(p_req);
	}
}
